package com.leetcode.array.smallestlength.demo2;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author Zan
 * @Create 2024/5/8 14:53
 * @ClassName: Test
 * @Description : https://leetcode.cn/problems/fruit-into-baskets/description/  水果成篮
 */
public class Test {
    public static void main(String[] args) {
        int[] arr = new int[]{3,3,3,1,2,1,1,2,3,3,4};
        Solution solution = new Solution();
        int i = solution.totalFruit(arr);
        System.out.println(i);
    }
}

class Solution {
    public int totalFruit(int[] fruits) {

        int size = fruits.length;
        Map<Integer, Integer> map = new HashMap<>();

        int start = 0;
        int sum = 0;
        for (int end = 0; end < size; end++) {
            map.put(fruits[end], map.getOrDefault(fruits[end], 0) + 1);
            while (map.size() > 2) {
                // 由于可能有从多个果树上摘下来的同一类别的果子，导致start需要++好几下
                // 因此只有当这个数量为0时，才能进行remove，从篮子里拿出去
                map.put(fruits[start], map.get(fruits[start]) - 1);
                if (map.get(fruits[start]) == 0) {
                    map.remove(fruits[start]);
                }
                start++;
            }
            sum = Math.max(sum, end - start + 1);
        }
        return sum;
    }
}
